package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.constant.RabbitConstant;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.model.mq.to.order.OrderCreateTO;
import com.atguigu.gmall.mq.service.RabbitService;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class OrderCloseListener {

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    RabbitService rabbitService;

    @RabbitListener(queues = {RabbitConstant.QUEUE_ORDER_DEAD})
    public void  orderListener(Message message, Channel channel) throws IOException {
        //拿到tag用于确认或者拒绝
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String json = new String(message.getBody());
        try {
            OrderCreateTO msg = JSONs.stringToObj(json, OrderCreateTO.class);
            log.info("正在关闭订单：id:{}， userId:{}",msg.getOrderId(),msg.getUserId());
            orderInfoService.cancelOrder(msg.getOrderId(),msg.getUserId());
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("关单处理失败；消息内容：{}",json);
            rabbitService.retry(deliveryTag,channel,json,5);
        }
    }
}
